package cn.wolfcode.car.business.service.impl;


import cn.wolfcode.car.business.domain.Appointment;
import cn.wolfcode.car.business.domain.Statement;
import cn.wolfcode.car.business.domain.StatementItem;
import cn.wolfcode.car.business.mapper.AppointmentMapper;
import cn.wolfcode.car.business.mapper.StatementItemMapper;
import cn.wolfcode.car.business.mapper.StatementMapper;
import cn.wolfcode.car.business.query.StatementItemQuery;
import cn.wolfcode.car.business.service.IStatementItemService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class StatementItemServiceImpl extends ServiceImpl<StatementItemMapper,StatementItem> implements IStatementItemService {

    @Autowired
    private StatementItemMapper statementItemMapper;
    @Autowired
    private StatementMapper statementMapper;
    @Autowired
    private AppointmentMapper appointmentMapper;
    @Override
    @ResponseBody
    public TablePageInfo<StatementItem> query(StatementItemQuery qo) {
        PageHelper.startPage(qo.getPageNum(),qo.getPageSize());
        QueryWrapper<StatementItem> statementItemQueryWrapper = new QueryWrapper<>();
        statementItemQueryWrapper.eq(qo.getStatementId() != null,"statement_id",qo.getStatementId());
        return new TablePageInfo<StatementItem>(statementItemMapper.selectList(statementItemQueryWrapper));
    }

    /**
     * 明细保存
     * @param statementItems
     */
    @Override
    @Transactional
    public void save(List<StatementItem> statementItems) {
        //通过json封装list集合数据获取里面封装的值，把最后一条只带有优惠价格的数据排除掉
        StatementItem item = statementItems.remove(statementItems.size() - 1);
        //获取最后跳list最后一条数据带有优惠价格数据的值
        BigDecimal discountAmount = item.getItemPrice();
        //获取结算单的id,并通过id去获取结算单的对象
        Statement statement = statementMapper.selectById(item.getStatementId());
        //判断是否客户处于消费中，只有消费中才能进行保存操作
        if (Statement.STATUS_PAID.equals(statement.getStatus())) {
            throw new BusinessException("不能对已支付的再进行支付!");
        }
        //获取总消费金额
        BigDecimal totalAmount = new BigDecimal("0.0");
        //总数量
        BigDecimal totalQuantity = new BigDecimal("0");
        //删除之前表存在的数据
        QueryWrapper<StatementItem> statementItemQueryWrapper = new QueryWrapper<>();
        statementItemQueryWrapper.eq("statement_id",statement.getId());
        statementItemMapper.delete(statementItemQueryWrapper);
        if (statementItems.size() > 0){
            //说明有明细项
            for (StatementItem statementItem : statementItems) {
                statementItemMapper.insert(statementItem);
                //统计总消费金额
                totalAmount = totalAmount.add(item.getItemPrice().multiply(statement.getTotalQuantity()));
                //统计总体数量
                totalQuantity = totalQuantity.add(statementItem.getItemQuantity());
            }
        }

        //判断优惠价格小于总消费金额
        if (discountAmount.compareTo(totalAmount) < 0) {
            throw new BusinessException("优惠价格不能超过总消费金额！");
        }

        //更新总消费金额，statementId，折扣价，总体数量
        UpdateWrapper<Statement> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",statement.getId());
        wrapper.set("total_amount",totalAmount);
        wrapper.set("total_quantity",totalQuantity);
        wrapper.set("discount_amount",discountAmount);
        statementMapper.update(null,wrapper);
    }

    /**
     * 支付功能
     * @param statementId
     */
    @Override
    @Transactional
    public void payStatement(Long statementId) {
        Statement statement = statementMapper.selectById(statementId);
        if (Statement.STATUS_PAID.equals(statement.getStatus())) {
            throw new BusinessException("只有在消费状态下才能进行消费操作，已支付过的无法再进行操作！");
        }
        UpdateWrapper<Statement> statementUpdateWrapper = new UpdateWrapper<>();
        statementUpdateWrapper.eq("id",statementId);
        statementUpdateWrapper.set("payee_id",ShiroUtils.getUserId());
        statementUpdateWrapper.set("status",Statement.STATUS_PAID);
        statementUpdateWrapper.set("pay_time",new Date());
        statementMapper.update(null,statementUpdateWrapper);
        //判断是否为预约下的订单
        if (statementMapper.selectById(statement.getAppointmentId()) != null) {
            UpdateWrapper<Appointment> wrapper = new UpdateWrapper<>();
            wrapper.eq("id",statement.getAppointmentId());
            wrapper.set("status",Appointment.STATUS_SETTLE);
            appointmentMapper.update(null,wrapper);
        }
    }
}
